<template>
  <div class="IFrame">
    <iframe
      :src="props.url"
      id="iframe"
      ref="iframeRef"
      frameborder="false"
      width="100%"
      scrolling="no"
    ></iframe>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, onUnmounted, ref, watch } from "vue"
import type { IIFrameConfig } from "./type"

const iframeRef = ref()

const props = withDefaults(defineProps<IIFrameConfig>(), {})

/**
 * 改变Iframe高度的函数
 * @param height 屏幕变化的高度
 */
function changeFrameHeight(height: number) {
  // iframeRef.value.height = document.documentElement.clientHeight
  iframeRef.value.height = height
}

// 屏幕resize的节流标识
let resizeTimeout: number

nextTick(() => {
  const iWindow = iframeRef.value.contentWindow // 获取iframe的window对象
  console.log("iWindow", iWindow)

  const iDoc = iWindow.document // 获取iframe的dom对象
  console.log("iDoc", iDoc)
})

// 监听屏幕变化
const elementToObserve = document.documentElement // 或者替换为要观察大小变化的其他元素
const resizeObserver = new ResizeObserver((entries) => {
  clearTimeout(resizeTimeout)

  resizeTimeout = setTimeout(() => {
    for (const entry of entries) {
      const windowHeight = entry.contentRect.height
      console.log(windowHeight)
      changeFrameHeight(windowHeight)
    }
  }, 300)
})

onMounted(() => {
  resizeObserver.observe(elementToObserve)
})

onUnmounted(() => {
  // 清除resizeObserver监听
  resizeObserver.unobserve(elementToObserve)

  // 清除可能存在的setTimeout
  clearTimeout(resizeTimeout)
})
</script>

<style lang="less" scoped>
.IFrame {
  // iframe {
  //   height: 100vh;
  // }
}
</style>
